import { getAccount, setAccount, getToken, setToken, removeToken, getUser, setUser, getAuthority, setAuthority, getOrderOpenedRow, setOrderOpenedRow } from '@/utils/auth'
import { get, post } from '@/utils/http'
import { api } from '@/api'

const user = {
  state: {
    token: getToken(),
    account: getAccount(),
    user: getUser(),
    authority: getAuthority(),
    orderOpenedRow: getOrderOpenedRow(),
    name: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_AUTHORITY: (state, authority) => {
      state.authority = authority
    },
    SET_ORDEROPENEDROW: (state, orderOpenedRow) => {
      state.orderOpenedRow = orderOpenedRow
    }
  },

  actions: {
    // 登录
    Login({ commit }, user) {
      console.log(user)
      const token = 'Basic ' + user.token + '_' + user.userId
      setToken(token)
      commit('SET_TOKEN', token)
      setUser(user)
      commit('SET_USER', user)
    },
    Remember({ commit }, account) {
      setAccount(account)
      commit('SET_ACCOUNT', account)
    },
    OpenRow({ commit }, rowIndex) {
      setOrderOpenedRow(rowIndex)
      commit('SET_ORDEROPENEDROW', rowIndex)
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        get(api.PERMISSION).then(
          res => {
            if (res.result && res.result.pageRoute && res.result.pageRoute.length > 0) {
              console.log(res.result)
              commit('SET_ROLES', res.result.pageRoute)
              // commit('SET_ROLES', ['all'])
              setAuthority(res.result)
              commit('SET_AUTHORITY', res.result)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
            resolve(res.result.pageRoute)
          }
        )
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        get(api.LOGOUT).then(
          () => {
            commit('SET_ROLES', [])
            commit('SET_AUTHORITY', {})
            commit('SET_ROUTERS', [])
            removeToken()
            resolve()
            location.reload()
          }
        )
      })
    }
  }
}

export default user
